package com.nirvana.item;

import com.nirvana.factory.ItemFactory;
import com.nirvana.type.ItemType;

import javax.swing.*;
import java.awt.event.ItemEvent;

public abstract class AbstractItem {
    protected CommonItem commonItem;
    protected final JPanel itemPanel = new JPanel();
    protected final JRadioButton propertyRadioButton = new JRadioButton();
    protected final JTextField propertyNameTextField = new JTextField();

    public AbstractItem() {
        commonItem = ItemFactory.getCommonItem(getItemType());
        itemPanel.setLayout(commonItem.panelTemplate.getLayout());
        propertyRadioButton.setHorizontalAlignment(commonItem.radioButtonTemplate.getHorizontalAlignment());
        commonItem.buttonGroup.add(propertyRadioButton);
        propertyRadioButton.addItemListener(this::defPropertyRadioButtonItemChange);
        itemPanel.add(propertyRadioButton, "cell 0 0");
        if (commonItem.itemList.isEmpty()) {
            propertyRadioButton.setSelected(true);
        }
        propertyNameTextField.setText(commonItem.textFieldTemplate.getText());
        itemPanel.add(propertyNameTextField, "cell 1 0,growx");
        commonItem.itemList.add(this);
    }

    public void init() {}

    protected String getConstraintsStr(int column) {
        return "cell " + column + " 0,growx";
    }

    protected abstract ItemType getItemType();
    public abstract void copy(AbstractItem item);

    private void defPropertyRadioButtonItemChange(ItemEvent event) {
        if (event.getStateChange() == ItemEvent.SELECTED) {
            commonItem.itemList.forEach(item -> item.itemPanel.setBackground(null));
            itemPanel.setBackground(commonItem.selectedBackgroudColor);
            commonItem.curSelectedItem = this;
        }
    }

    public String getPropertyName() {
        return propertyNameTextField.getText();
    }
}
